package com.hcy.rabbitruntimeapi.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hcy.rabbitruntimeapi.center.CenterHandlerLink;
import com.hcy.rabbitruntimeapi.model.dto.WebSocketKey;
import com.hcy.rabbitbasicmodel.common.MyWebSocketMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Queue;
import java.util.concurrent.*;

/**
 * @Author huchenying
 * @Description
 * @Date 2021/12/15 13:21
 */
@Component
@ChannelHandler.Sharable
//这里的类型 表示一个文本帧 TextFrame  还有其他类型，选择使用
public class MyWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(MyWebSocketFrameHandler.class);

    public static final ConcurrentHashMap<WebSocketKey, Channel> channels = new ConcurrentHashMap<>();
    public static final ConcurrentHashMap<Channel, WebSocketKey> webSocketKeys = new ConcurrentHashMap<>();

    public BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>();
    public ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 0, TimeUnit.SECONDS, blockingQueue, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("websocket handler");
            return thread;
        }
    }, new ThreadPoolExecutor.CallerRunsPolicy());

    @Autowired
    CenterHandlerLink centerHandlerLink;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        logger.debug("服务器端收到消息 ->  [{}]", msg.text());
        //回复消息
        try {
            String text = msg.text();
            Object parse = JSON.parse(text);
            MyWebSocketMessage myWebSocketMessage = JSON.parseObject(JSON.toJSONString(parse), MyWebSocketMessage.class);
//            Message message = JSON.parseObject(msg.text(), Message.class);
            //通过线程池执行
            MyHandlerData myHandlerData = new MyHandlerData(centerHandlerLink, myWebSocketMessage);
            executor.submit(myHandlerData);
//            centerHandlerLink.handler(myWebSocketMessage);
        } catch (Exception e) {
            logger.error("msg parse error reason-> {}", e.getMessage());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("websocket发生异常");
//        channels.remove(webSocketKeys.get(ctx.channel()));
//        webSocketKeys.remove(ctx.channel());
        ctx.close();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
//        channels.remove(webSocketKeys.get(ctx.channel()));
//        webSocketKeys.remove(ctx.channel());
    }

}

